package jse.ou;

import org.junit.Test;

import java.io.*;

/**
* @desc    测试输出流
* @author kanggw
* @datetime 2016/8/17,8:52
*/
public class TestOutPut {

    @Test
    public void test1() throws IOException {

        //找到目标文件
        File file = new File("c:" + File.separatorChar + "aaa.txt");
        //建立通道
        FileOutputStream fos = new FileOutputStream(file);
        //输出
        fos.write('h');
        fos.write('h');
        fos.write('h');
        fos.write('h');
        //关闭
        fos.close();
    }

    /**
    * @desc   以缓冲数组方式写出
    * @author kanggw
    * @datetime 2016/8/17,8:58
    */
    @Test
    public void test2() throws IOException {

        //找到目标文件
        File file = new File("c:" + File.separatorChar + "aaa.txt");
        //建立通道
        FileOutputStream fos = new FileOutputStream(file);
        //输出
        String data = "hello world";
        byte[] bytes = data.getBytes();
        fos.write(bytes);
        //关闭
        fos.close();
    }

    /**
     * @desc   拷贝图片
     * @author kanggw
     * @datetime 2016/8/17,8:58
     */
    @Test
    public void test3()   {

        //找到目标文件 C:\Users\Public\Pictures\Sample Pictures
        File file = new File("c:" + File.separatorChar + "Users"+File.separatorChar+"Public"+File.separatorChar+"Pictures"+File.separator+"Sample Pictures"+File.separator+"kaola.jpg");
        //建立输入通道
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file);
            //建立输出通道
             fos = new FileOutputStream("c:" + File.separator + "kaola.jpg");

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        //输入
        byte[] bytes = new byte[1024];
        int length = 0;
        try {
            while ((length = fis.read(bytes)) != -1) {
                //输出
                fos.write(bytes,0,length);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            /**先开后关，先关后开*/
            if (fos == null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fis == null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        System.out.println("拷贝完毕！");
        //关闭

    }
}
